import webapp2
from google.appengine.api import users
from util.webapp import ShopkeepApplication, ShopkeepHandler
from models.Collection import Collection
from models.Item import Item

class CollectionPage(ShopkeepHandler):
	def get(self):
		user = users.get_current_user()
		action = self.request.GET.get("action", "view")
		type, id = self.type_and_id
		if type not in range(0, 3) or id == -1:
			self.abort(400)

		c = Collection.get_by_id(id)
		if c is None or (not c.canView()):
			self.abort(400)

		data = {"collection_type":type, "collection_id":id}
		items = []
		data["items"] = items
		for i in c.getItems():
			item = {}
			item["title"] = i.title
			item["seller"] = i.seller
			item["id"] = i.id
			
			if item.status == Item.STATUS_INACTIVE:
				item["status"] = "inactive"
			elif item.status == STATUS_EXPIRED:
				item["status"] = "expired"
			else:
				item["status"] = "active"

			items.append(item)

		if action == "view":
			self.render_response("collection_get.html", data)
		elif action == "delete":
			# if given item id then remove item from collection. else delete collection
			item_id = self.request.GET.get("item", "")
			if item_id != "":
				try:
					item_id = int(item_id)
				except ValueError:
					self.abort(400)
				for i in c.getItems()
					if i.id == item_id
						c.removeItem(i)
						c.put()
			else:
				# remove this collection
				c.delete()
				self.redirect(self.request.host_url)
		else:
			self.abort(400)

	@webapp2.cached_property
	def type_and_id(self):
		info = self.request.path.split('/')
		assert info[0] == ''

		if len(info) == 4:
			try:
				type = int(info[2])
				id = int(info[3])
			except ValueError:
				self.abort(400)
			return (type, id)
		else:
			return (-1, -1)
		
# check that route is correct for collection
app = ShopkeepApplication([('/collection/.+/.+', CollectionPage)])
